package com.bckj.fastboot.iot.mq.redis.listener;

import com.bckj.fastboot.core.redis.RedisOps;
import com.bckj.fastboot.iot.common.constant.IotMQConstants;
import com.bckj.fastboot.iot.common.dto.msg.IotDeviceMessage;
import com.bckj.fastboot.iot.common.mq.consumer.IotDeviceMessageConsumer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * IotDeviceMessageListener
 *
 * @author wfc
 **/
@Slf4j
@Component
public class IotDeviceMessageListener implements ApplicationRunner {

    @Resource
    private RedisOps redisOps;
    @Resource
    private IotDeviceMessageConsumer iotDeviceMessageConsumer;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("==================== 启动设备信息监听器 ====================");
        alarmInfoMessageReceiver();
    }

    private void alarmInfoMessageReceiver() {
        new Thread(() -> {
            for (; ; ) {
                try {
                    IotDeviceMessage message = (IotDeviceMessage) redisOps.lrPop(IotMQConstants.IOT_DEVICE_TOPIC, 30, TimeUnit.SECONDS);
                    if (message == null) {
                        log.info("没有收到设备信息");
                        continue;
                    }
                    log.info("收到报警通知:{}", message);
                    iotDeviceMessageConsumer.onMessage(message);
                } catch (Exception e) {
                    log.error("物联设备异常", e);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        log.error("物联设备异常1", ex);
                    }
                }
            }
        }).start();
    }
}
